package com.stars.easyms.demo.rest.service.sentinel;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.stars.easyms.demo.rest.dto.input.sentinel.SentinelDemo7Input;
import com.stars.easyms.demo.rest.dto.output.sentinel.SentinelDemo7Output;
import com.stars.easyms.rest.RestService;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Service
public class SentinelDemo7Service implements RestService<SentinelDemo7Input, SentinelDemo7Output> {

    private static final String RESOURCE_NAME = SentinelDemo7Service.class.getSimpleName();

    @Override
    public SentinelDemo7Output execute(SentinelDemo7Input input) {
        defineAuthorityRules(input);
//        ContextUtil.enter(RESOURCE_NAME, input.getSysSource());
        String retMsg;
        Entry entry = null;
        try {
            entry = SphU.entry(RESOURCE_NAME);
            retMsg = "通过";
        } catch (BlockException ex) {
            retMsg = "拦截";
        } finally {
            if (entry != null) {
                entry.exit();
            }
            ContextUtil.exit();
        }
        SentinelDemo7Output output = new SentinelDemo7Output();
        System.out.println(retMsg);
        return null;
    }

    private void defineAuthorityRules(SentinelDemo7Input input) {
        AuthorityRule rule = new AuthorityRule();
        rule.setResource(RESOURCE_NAME);
        rule.setStrategy(input.getStrategy());
        rule.setLimitApp(input.getLimitApp());
        AuthorityRuleManager.loadRules(Collections.singletonList(rule));
    }
}